class ApplicationController < ActionController::Base
  protect_from_forgery

  before_filter :user_setup

  def user_setup
    User.current = find_current_user
  end

  def find_current_user
    user = nil
    if session[:user_id]
      user = (User.find(session[:user_id]) rescue nil)
    end
  end

  def logged_user=(user)
    reset_session
    if user && user.is_a?(User)
      User.current = user
      start_user_session(user)
    else
      User.current = nil
    end
  end

  def logout_user
    self.logged_user = nil
  end

  def start_user_session(user)
    session[:user_id] = user.id
    session[:ctime] = Time.now.utc.to_i
    session[:atime] = Time.now.utc.to_i
  end

  def require_login
    if User.current.nil?
      url = url_for(params)

      respond_to do |format|
        format.html { redirect_to :controller => "account", :action => "login", :back_url => url }
        format.json { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Twitter Fake API"' }
      end
      return false
    end
    true
  end
end